__doc__ =   """ Function to superimpose entities.
            """

from Einput import einput
from EntityManipulate import entities_dot_matrix
from Math import get_rotation_matrix, kappa_from_rotation_matrix
from numpy import array

def auto_superimpose(entity_1, entity_2, at_id ='CA', rotate =True):
    residues_1 = einput(entity_1, 'R')
    residues_2 = einput(entity_2, 'R')
    resids_1 = dict([(r.res_id, r) for r in residues_1])
    resids_2 = dict([(r.res_id, r) for r in residues_2])
    common =  set(resids_1.keys())
    common.intersection_update(resids_2.keys())
    coords_1, coords_2 = [], []
    for resid in common:
        residue_1 = resids_1[resid]
        residue_2 = resids_2[resid]
        try:
            atom1 = residue_1._select_children(at_id, 'eq', 'at_id').values()[0].coords
            atom2 = residue_2._select_children(at_id, 'eq', 'at_id').values()[0].coords
            coords_1.append(atom1)
            coords_2.append(atom2)
        except IndexError:
            pass
    coords_1 = array(coords_1)
    coords_2 = array(coords_2)
    mtrx, rmsd = get_rotation_matrix(coords_1, coords_2)
    if rotate:
        entity_1.set_coords()
        entity_1.recursive_move(entity_1.get_coords())
        entity_2.set_coords()
        entity_2.recursive_move(entity_2.get_coords())
        entities_dot_matrix(entity_2, mtrx)
    kappa = kappa_from_rotation_matrix(mtrx)
    return (kappa, rmsd)